package cn.qiba.sms.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.qiba.sms.AppCtx;
import cn.qiba.sms.bo.common.RequestData;
import cn.qiba.sms.bo.common.SmsResult;
import cn.qiba.sms.controller.common.AuthenticatedController;
import cn.qiba.sms.core.enums.ChannelEnums;
import cn.qiba.sms.db.dao.SmsInfoRepository;
import cn.qiba.sms.db.entity.SmsInfo;
import cn.qiba.sms.service.ISmsService;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/send")
public class SmsController extends AuthenticatedController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${sms.limit.send.ip}")
    private String[] ip;

    @Autowired
    private SmsInfoRepository smsInfoRepository;


    @PostMapping("/sms")
    @ResponseBody
    SmsResult send(@RequestBody(required = false) String param,HttpServletRequest request){
        String reqIp = request.getAttribute("ip").toString();
        if(ip != null && ip.length > 0 && !ArrayUtil.contains(ip,reqIp)){
            logger.info("请求ip不合法：{}",reqIp);
            return ERROR(StrUtil.format("请求ip不合法：{}",reqIp));
        }
        JSONObject json = new JSONObject();
        RequestData requestData = JSONObject.parseObject(param,RequestData.class);
        Map<String,Object> data = requestData.getData();
        Object obj = data.get("templateParam");
        if(obj != null){
            data.put("templateParam",JSONObject.parseObject(obj.toString(), LinkedHashMap.class));
        }
        requestData.setData(data);
        ChannelEnums channel = ChannelEnums.getByCode(requestData.getChannel());
        if(channel == null){
            logger.info("根据【{}】未获取到所匹配的通道信息",requestData.getChannel());
            return INPUT(StrUtil.format("根据【{}】未获取到所匹配的通道信息",requestData.getChannel()));
        }

        SmsInfo smsInfo = new SmsInfo(data.get("phoneNumber").toString(),JSONObject.toJSONString(data.get("templateParam")==null?"":data.get("templateParam")),(String)data.get("templateCode"),requestData.getChannel(),reqIp);
        smsInfoRepository.save(smsInfo);
        ISmsService smsService = (ISmsService) AppCtx.getBean(channel.getService());

        SmsResult smsResult = smsService.send(JSONObject.parseObject(JSONUtil.toJsonStr(requestData.getData()),channel.getBo()));
        if(SmsResult.E.SUCCESS.getCode().equals(smsResult.getCode())){
            smsInfo.setStatus(SmsInfo.I.STATUS_SUCCESS);
            smsInfo.setSuccessTime(new Date());
            smsInfo.setMsg("发送成功");
        }else{
            smsInfo.setStatus(SmsInfo.I.STATUS_ERROR);
            smsInfo.setMsg(smsResult.getMsg());
        }
        smsInfoRepository.save(smsInfo);
        return smsResult;
    }

}

